const util = require('../../utils/util');
const DeptService = require('../../service/system/dept.service');

// 创建部门
async function createDept(ctx) {
	const { userId } = util.decodeToken(ctx);
	const { pid, name, sort, remark, leaders } = ctx.request.body;
	if (!name || pid === undefined) {
		return util.fail(ctx, '部门名称和父部门 ID 不能为空');
	}
	const result = await DeptService.createDept({ pid, name, sort, remark, leaders, create_id: userId });
	util.success(ctx);
}

// 获取部门树状列表
async function listDepts(ctx) {
	const depts = await DeptService.getDeptTree();
	util.success(ctx, depts);
}

// 更新部门
async function updateDept(ctx) {
	const { userId } = util.decodeToken(ctx);
	const { id, pid, name, deep, sort, remark, isLock, leaders } = ctx.request.body;
	if (!id) return util.fail(ctx, '部门 ID 不能为空');
	const result = await DeptService.updateDept(id, { pid, name, deep, sort, remark, isLock, leaders, update_id: userId });
	util.success(ctx);
}

// 删除部门
async function deleteDept(ctx) {
	const { userId } = util.decodeToken(ctx);
	const { ids } = ctx.request.body;
	if (!ids || !Array.isArray(ids) || ids.length === 0) {
		return util.fail(ctx, '请提供有效的部门 ID 数组');
	}
	await DeptService.deleteDept(ids, userId);
	util.success(ctx);
}

// 获取单个部门信息
async function getDeptById(ctx) {
	const { id } = ctx.params;
	if (!id) {
		return util.fail(ctx, '部门 ID 无效');
	}
	const dept = await DeptService.getDeptById(Number(id));
	if (!dept) {
		return util.fail(ctx, '部门不存在或已被删除');
	}
	util.success(ctx, dept);
}

// 获取上级部门树（下拉框用）
async function getDeptTreeForSelect(ctx) {
	const { excludeNodeId } = ctx.request.query;
	const tree = await DeptService.getDeptTreeForSelect(excludeNodeId ? Number(excludeNodeId) : null);
	util.success(ctx, tree);
}

// 获取负责人穿梭框-全部用户
async function getDeptLeader(ctx) {
	const { username, nickname } = ctx.request.query;
	const leaders = await DeptService.getDeptLeader({ username, nickname });
	util.success(ctx, { leaderInfoVOS: leaders });
}

module.exports = { createDept, listDepts, updateDept, deleteDept, getDeptById, getDeptTreeForSelect, getDeptLeader };
